package wpmp.auth.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Component;

import wcommons.beanutils.BeanUtils;
import wpmp.auth.Statics;
import wpmp.auth.cache.CacheManager;
import wpmp.auth.dao.CodeDao;
import wpmp.utils.quickbean.Code;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 3:06:41 PM Dec 26, 2012
 */
@Component
public class CodeService extends BaseService {

	@Autowired
	private CacheManager cacheManager;

	private CodeDao dao;

	public CodeDao getDao() {
		return dao;
	}

	@Autowired
	public void setDao(CodeDao dao) {
		this.dao = dao;
	}

	@SuppressWarnings("unchecked")
	public List<Code> queryForList(String sortType) {
		final String key = Statics.CODE_ + sortType;
		// 优先缓存
		List<Code> results = (List<Code>) cacheManager.get(key);
		if (results != null) {
			return results;
		}

		results = new ArrayList<Code>();

		final SqlRowSet rs = dao.queryForRowSet(sortType);
		while (rs.next()) {
			final Code result = new Code();
			BeanUtils.copySqlRowSetToBean(result, rs);
			results.add(result);
		}

		return results;
	}

	public Code queryForObject(String sortType, String value) {
		final List<Code> results = this.queryForList(sortType);

		if (CollectionUtils.isEmpty(results)) {
			return null;
		}

		for (Code result : results) {
			if (StringUtils.equals(result.getValue(), value)) {
				return result;
			}
		}

		return null;
	}

}
